package com.ikun.kunpicturebackend.manager.websocket.disruptor;

import com.ikun.kunpicturebackend.domain.User;
import com.ikun.kunpicturebackend.manager.websocket.model.PictureEditRequestMessage;
import com.lmax.disruptor.RingBuffer;
import com.lmax.disruptor.dsl.Disruptor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketSession;

import javax.annotation.PreDestroy;
import javax.annotation.Resource;

/**
 * 事件生产者
 */
@Component
@Slf4j
public class PictureEditEventProducer {

    @Resource
    private Disruptor<PictureEditEvent> pictureEditEventDisruptor;

    /**
     * 发布消息
     * @param pictureEditRequestMessage
     * @param session
     * @param user
     * @param pictureId
     */
    public void publishEvent(PictureEditRequestMessage pictureEditRequestMessage, WebSocketSession session,
                             User user, Long pictureId) {
        // 获取RingBuffer
        RingBuffer<PictureEditEvent> ringBuffer = pictureEditEventDisruptor.getRingBuffer();
        // 获取可以生成的位置
        long sequence = ringBuffer.next();
        try {
            // 获取事件
            PictureEditEvent event = ringBuffer.get(sequence);
            // 设置事件内容
            event.setPictureEditRequestMessage(pictureEditRequestMessage);
            event.setSession(session);
            event.setUser(user);
            event.setPictureId(pictureId);
        } finally {
            // 发布事件
            ringBuffer.publish(sequence);
        }
    }

    /**
     * 优雅停机
     */
    @PreDestroy
    public void close() {
        pictureEditEventDisruptor.shutdown();
    }

}
